﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace GnToolControls.Convert
{
	public class ConvertComposedcs
	{
		private List<ConvertXmlLoadEvent> _convertXmlLoadFunc = new List<ConvertXmlLoadEvent>();
		private List<ConvertItem> _convertSources = new List<ConvertItem>();

		public ConvertComposedcs()
		{
			_convertXmlLoadFunc.Add( ConvertFileItem.LoadXml );
		}

		public bool AddSource( ConvertItem source )
		{
			if( IsExists( ref source ) )
				return false;

			_convertSources.Add( source );
			return false;
		}

		private bool IsExists( ref ConvertItem checkSource )
		{
			foreach(ConvertItem source in _convertSources)
			{
				if( source.IsEqual( checkSource ) )
				{
					return true;
				}
			}
			return false;
		}

		public bool SaveXml( String fileName )
		{
			XmlWriter writer = null;
			try
			{
				writer = XmlWriter.Create( fileName );
				if( writer == null )
					return false;
			}
			catch
			{
			}			
			
			try
			{
				writer.WriteComment( "Convert XML" );
				foreach( ConvertItem item in _convertSources )
				{
					item.SaveXml( writer );
				}
			}
			catch// (System.Exception ex)
			{
				return false;
			}
			finally
			{
				writer.Close();
			}
			return true;
		}

		public bool LoadXml( String fileName )
		{
			XmlReader reader = XmlReader.Create( fileName );
			if( reader == null )
				return false;

			try
			{
				while( reader.Read() )
				{
					if( reader.IsStartElement() )
					{
						foreach( ConvertXmlLoadEvent loader in _convertXmlLoadFunc )
						{
							ConvertItem item = loader( reader, reader.Name );
							if( item != null )
							{
								_convertSources.Add(item);
								break;
							}
						}
					}
				}
			}
			catch// (System.Exception ex)
			{
				return false;
			}
			finally
			{
				reader.Close();
			}
			return true;
		}
	}
}
